const mysql = require('mysql')

const db = mysql.createConnection({
  host: '127.0.0.1',
  port: 3306,
  user: 'root',
  password: 'root',
  database: 'bailongtansq',
})

db.connect(err => {
  if (err) {
    console.warn('Connect Mysql Failure', err.toString())
    process.exit(0)
  }
  console.log('Connect Mysql Success')
})

/**
 * 存储方法
 * @param data
 * @returns {Promise<any>}
 */
db.save = function save(data = {}) {
  return new Promise((resolve, reject) => {
    db.query(
      'insert into bailongtan_ext_pachong(title, time, type, url, info) values (?, ?, ?, ?, ?)',
      [data.title, data.time, data.type, data.url, data.info],
      (err, rows, fields) => {
        if (err) {
          reject(err)
        } else {
          resolve({ rows, fields })
        }
      },
    )
  })
}

/**
 * 是否存在
 * @param data
 * @returns {Promise<any>}
 */
db.isExists = function isExists(data = {}) {
  return new Promise((resolve, reject) => {
    db.query(
      'select data_id from bailongtan_ext_pachong where url = ?',
      [data.url],
      (err, rows) => {
        if (err) {
          reject(err)
        } else {
          resolve(rows.length !== 0)
        }
      })
  })
}

module.exports = db
